<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&language=vi"></script> 
<link rel="stylesheet" media="all" type="text/css" href="/files/js/jquery.timepicker/jquery-ui-timepicker-addon.css" />
<script type="text/javascript" src="/files/js/jquery.timepicker/jquery-ui-timepicker-addon.js"></script>
<script type="text/javascript" src="/files/js/jquery.timepicker/jquery-ui-sliderAccess.js"></script>


<script>

    $(function(){    
        $("#Branch_time_open, #Branch_time_close").timepicker({
            //timeFormat: "hh:mm",
            //controlType: 'select',
            showButtonPanel: true,
            addSliderAccess: true,
            sliderAccessArgs: { touchonly: false },
            timeOnlyTitle: 'Chọn thời gian',
            timeText: 'Thời gian',
            hourText: 'Giờ',
            minuteText: 'Phút',
            closeText: 'Đóng',
            stepMinute: 10,
        });       



        var locationsDataGroupByCity = $.parseJSON('<?php echo json_encode(PublicLocation::model()->dataGroupByCity)?>');


        var citiesRefID = $.parseJSON('<?php echo json_encode($citiesRefID)?>');
        var districtsRefID = $.parseJSON('<?php echo json_encode($districtsRefID)?>');

        var districtsDataGroupByCity = $.parseJSON('<?php echo json_encode($districtsDataGroupByCity)?>');

        function kmcompare(a,b) {
            if (a.km < b.km) return -1;
            if (a.km > b.km) return 1;
            return 0;
        }


        function google_map(latlng) {
            var latlng = latlng.split(",");
            var lat = latlng[0];
            var lng = latlng[1];

            var center_position = new google.maps.LatLng(lat, lng);
            var marker_position = new google.maps.LatLng(lat, lng);
            var marker;
            var map;

            var mapOptions = {
                zoom: 15,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: center_position,

                panControl: false,
                zoomControl: true,
                //                          zoomControlOptions: {
                //                              style: google.maps.ZoomControlStyle.LARGE,
                //                              position: google.maps.ControlPosition.TOP_LEFT
                //                          },
                streetViewControl: false
            };

            map = new google.maps.Map(document.getElementById('map'), mapOptions);

            marker = new google.maps.Marker({
                map:map,
                draggable:true,
                animation: google.maps.Animation.DROP,
                position: marker_position,
                icon : new google.maps.MarkerImage('/files/img/red_flag.png',
                    new google.maps.Size(69,48),
                    new google.maps.Point(0,0),
                    new google.maps.Point(35,48)
                ),
                shadow: new google.maps.MarkerImage('/files/img/red_flag_shadow.png',
                    new google.maps.Size(97,48),
                    new google.maps.Point(0,0),
                    new google.maps.Point(35,48)
                )
            }); 
            google.maps.event.addListener(marker, 'click', function(){
                if (marker.getAnimation() != null) {
                    marker.setAnimation(null);
                } else {
                    marker.setAnimation(google.maps.Animation.BOUNCE);
                }
            });

            google.maps.event.addListener(marker, 'dragend', function(){
                var loc = marker.getPosition();
                var lat = roundNumber(loc.lat(),6);
                var lng = roundNumber(loc.lng(),6);
                $('#Branch_latlng').val(lat+','+lng);
                $('#latlng_view').val(lat+','+lng);

                // public location
                var city_id = $("#Branch_city_id").val();
                var locations = [];

                $("#Branch_publicLocations").html('');
                $.each(locationsDataGroupByCity[city_id], function(key, value){
                    var km = getDistanceFromLatLonInKm(lat, lng, value.lat, value.lng);
                    var km = roundNumber(km,3);
                    if(km <= <?php echo Yii::app()->params->kmNear?>){
                        var loc = {
                            km : km,
                            id: key,
                            name: value.name,
                            lat: value.lat,
                            lng: value.lng
                        }
                        locations.push(loc);
                    }
                });
                locations.sort(kmcompare);
                // set public location cookie
                $.cookie('branch_form_location', JSON.stringify(locations));

                // display pubic location 
                $.each(locations, function(index, loc){
                    //console.log(loc.km +' : '+loc.name+' : '+loc.lat+','+loc.lng);
                    var selected = (loc.km <= <?php echo Yii::app()->params->kmNearSelected?>) ? 'selected="selected"' : '';
                    $("#Branch_publicLocations").append('<option '+selected+' value="'+loc.id+'">'+loc.name+'</option>');   
                });






            });


        }
        google_map(<?php echo ($model->latlng) ? "'{$model->latlng}'" : 'citiesRefID[$("#Branch_city_id").val()].latlng'?>);


        $("#Branch_city_id").change(function(){
            var city_id = $(this).val();

            $("#Branch_district_id").html('');
            $.each(districtsDataGroupByCity[city_id], function(key, value){
                $("#Branch_district_id").append('<option value="'+key+'">'+value+'</option>');
            });

            google_map(citiesRefID[city_id].latlng);

            $('#address_full').val(citiesRefID[city_id].name);
            //$('#Branch_address').val('');

            $('#Branch_latlng').val(citiesRefID[city_id].latlng);
            $('#latlng_view').val(citiesRefID[city_id].latlng);

            // public location
            $("#Branch_publicLocations").html('');
            if(typeof locationsDataGroupByCity[city_id] != 'undefined'){
                $.each(locationsDataGroupByCity[city_id], function(key, value){
                    $("#Branch_publicLocations").append('<option value="'+key+'">'+value.name+'</option>');
                });  
            }

        });

        $("#Branch_district_id").change(function(){
            var district_id = $(this).val();
            var city_id = $("#Branch_city_id").val();

            if(district_id == 0) return false;

            var latlng = districtsRefID[district_id].latlng != '' ? districtsRefID[district_id].latlng : citiesRefID[city_id].latlng;
            google_map(latlng);

            $('#address_full').val(districtsRefID[district_id].name + ', '+ citiesRefID[city_id].name);
            $('#Branch_address').focus();

            $('#Branch_latlng').val(districtsRefID[district_id].latlng);
            $('#latlng_view').val(districtsRefID[district_id].latlng);
        });

        $("#Branch_address").bind('blur keypress keyup paste', function(){
            var city_id =       $("#Branch_city_id").val();
            var district_id =   $("#Branch_district_id").val();
            if(district_id > 0){
                $('#address_full').val($(this).val() +', '+ districtsRefID[district_id].name + ', '+ citiesRefID[city_id].name);
            }
        }).keyup();

    });   
</script>


<?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'branch-form',
        'enableClientValidation'=>true,
        'clientOptions'=>array(
            'validateOnSubmit'=>true,
        ),
        'enableAjaxValidation'=>false,
        'htmlOptions' => array('class' => 'stdform stdformsmall', 'enctype' => 'multipart/form-data')
    )); ?>
    
<div class="row-fluid">
    <div class="span12">
            <?php echo $form->errorSummary($model);?>
    </div>
</div>

<?php if($shop):?>   
    <div class="row-fluid">
        <div class="span6">
            <h4 class="widgettitle">Thông tin cửa hàng</h4>
            <div class="widgetcontent">                
                <div class="par control-group">
                    <label for="Branch_shop_name" class="control-label required">Tên cửa hàng <span class="required">*</span></label>
                    <div class="controls">
                        <?php echo $form->textField($model,'shop_name',array('maxlength'=>255, 'class' => 'input')); ?>
                        <?php echo $form->error($model,'shop_name');?>
                    </div>
                </div>
                <div class="par control-group">
                    <label for="Branch_shop_name" class="control-label required">Sub-domain</label>
                    <div class="controls">
                        <?php echo $form->textField($model,'shop_sub',array('maxlength'=>255, 'class' => 'input')); ?>
                        <?php echo $form->error($model,'shop_sub');?>
                    </div>
                </div>
                <div class="par control-group">
                    <label for="Branch_shop_name" class="control-label required">Domain</label>
                    <div class="controls">
                        <?php echo $form->textField($model,'shop_domain',array('maxlength'=>255, 'class' => 'input')); ?>
                        <?php echo $form->error($model,'shop_domain');?>
                    </div>
                </div>
                <div class="par control-group">
                    <label for="Branch_shop_name" class="control-label required">Website</label>
                    <div class="controls">
                        <?php echo $form->textField($model,'shop_website',array('maxlength'=>255, 'class' => 'input')); ?>
                        <?php echo $form->error($model,'shop_website');?>
                    </div>
                </div>
                <div class="par control-group">
                    <label for="Branch_shop_name" class="control-label required">Email</label>
                    <div class="controls">
                        <?php echo $form->textField($model,'shop_email',array('maxlength'=>255, 'class' => 'input')); ?>
                        <?php echo $form->error($model,'shop_email');?>
                    </div>
                </div>
                <div class="par control-group">
                    <label for="Branch_shop_name" class="control-label required">Giao diện</label>
                    <div class="controls">
                        <?php echo $form->dropDownList($model,'shop_theme', Theme::model()->themeData, array('empty' => '')); ?>
                        <?php echo $form->error($model,'shop_theme');?>
                    </div>
                </div>
                <div class="par control-group">
                    <label for="Branch_shop_name" class="control-label required">Layout</label>
                    <div class="controls">
                        <?php echo $form->dropDownList($model,'shop_layout', Shop::model()->layoutData, array('empty' => '')); ?>
                        <?php echo $form->error($model,'shop_layout');?>
                    </div>
                </div>
            </div>
        </div>
        <div class="span6">
            <h4 class="widgettitle">Ghi chú cho chi nhánh</h4>
            <div class="widgetcontent">                
                <div class="par control-group">
                    <?php //echo $form->labelEx($model,'note', array('class' => 'control-label')); ?>
                    <div class="controls">
                        <?php echo $form->textArea($model,'note', array('style' => 'width: 97%; height: 200px')); ?>
                    </div>
                </div>
                <div class="par control-group">
                    <label for="Branch_need_img" class="control-label">Cần thêm ảnh</label>
                    <div class="controls">
                        <?php echo $form->checkBox($model,'need_img'); ?>
                    </div>
                </div>
                <div class="par control-group">
                    <label for="Branch_need_img" class="control-label">Cần thêm info</label>
                    <div class="controls">
                        <?php echo $form->checkBox($model,'need_info'); ?>
                    </div>
                </div>

                <div class="par control-group">
                    <?php echo $form->labelEx($model,'phone', array('class' => 'control-label')); ?>
                    <div class="controls">
                        <?php echo $form->textField($model,'phone',array('maxlength'=>255, 'class' => 'input')); ?>
                        <?php echo $form->error($model,'phone');?>
                    </div>
                </div>
                
                <div class="par control-group">
                    <?php echo $form->labelEx($model,'status', array('class' => 'control-label')); ?>
                    <div class="controls">
                        <?php echo $form->dropDownList($model, 'status', $model->statusData, array('class' => 'input uniformselect')); ?>
                        <?php echo $form->error($model,'status');?>                     
                    </div>
                </div>
            </div>
        </div>
    </div>

    <ul class="nav nav-tabs tab-branch">
        <?php foreach($shop->branches as $br):?>
            <li <?php if($model->id == $br->id) echo 'class="active"'?>>
                <a href="<?php echo $br->getAdminUrl('update')?>"><?php echo $br->name?></a>
            </li>
            <?php endforeach?>
        <?php if($model->isNewRecord):?>
            <li class="active">
                <a>Chi nhánh mới</a>
            </li>
            <?php endif?>
        <li id="add-more-branch"><a href="<?php echo $this->createUrl('/admin/branch/create', array('shop_id' => $shop->id))?>"><i class="icon-plus"></i> Thêm chi nhánh</a></li>
    </ul>

<?php endif?>    



<div class="row-fluid">
    <div class="span6">
        <h4 class="widgettitle"><?php echo !$shop ? 'Thông tin cửa hàng' : 'Thông tin chi nhánh'?></h4>
        <div class="widgetcontent">                


            <div class="shop-form-grid-attrs">
                <?php if($model->foody):?>
                <div class="par control-group">
                    <label for="Branch_foody_id" class="control-label required">Foody Url</label>
                    <div class="controls">
                        <a href="<?php echo $model->foody->url?>" target="_blank">Go to source link</a>
                    </div>
                </div>
                <?php endif?>
            
                <div class="par control-group">
                    <label for="Branch_name" class="control-label required">
                        <?php echo !$shop ? 'Tên cửa hàng' : 'Tên chi nhánh'?>
                        <span class="required">*</span>
                    </label>
                    <div class="controls">
                        <?php echo $form->textField($model,'name',array('maxlength'=>255, 'class' => 'input')); ?>
                        <?php echo $form->error($model,'name');?>
                    </div>
                </div>

                <div class="par control-group">
                    <?php echo $form->labelEx($model,'cats', array('class' => 'control-label')); ?>
                    <div class="controls">
                        <?php echo $form->dropDownList($model,'cats', PostCat::model()->data, array('maxlength'=>255, 'class' => 'input', 'multiple' => 'multiple', 'size' => count(PostCat::model()->data))); ?>
                        <?php echo $form->error($model,'cats');?>
                    </div>
                </div>


                <div class="par control-group">
                    <?php echo $form->labelEx($model,'time_open', array('class' => 'control-label')); ?>
                    <div class="controls">
                        <?php echo $form->textField($model,'time_open',array('maxlength'=>255, 'class' => 'input')); ?>
                        <?php echo $form->error($model,'time_open');?>
                    </div>
                </div>
                <div class="par control-group">
                    <?php echo $form->labelEx($model,'time_close', array('class' => 'control-label')); ?>
                    <div class="controls">
                        <?php echo $form->textField($model,'time_close',array('maxlength'=>255, 'class' => 'input')); ?>
                        <?php echo $form->error($model,'time_close');?>
                    </div>
                </div>

                <div class="par control-group">
                    <?php echo $form->labelEx($model,'price_avg_from', array('class' => 'control-label')); ?>
                    <div class="controls">
                        <?php echo $form->textField($model,'price_avg_from',array('maxlength'=>255, 'class' => 'input numeric format')); ?>
                        <?php echo $form->error($model,'price_avg_from');?>
                    </div>
                </div>
                <div class="par control-group">
                    <?php echo $form->labelEx($model,'price_avg_to', array('class' => 'control-label ')); ?>
                    <div class="controls">
                        <?php echo $form->textField($model,'price_avg_to',array('maxlength'=>255, 'class' => 'input numeric format')); ?>
                        <?php echo $form->error($model,'price_avg_to');?>
                    </div>
                </div>
                <div class="par control-group">
                    <?php echo $form->labelEx($model,'direction', array('class' => 'control-label ')); ?>
                    <div class="controls">
                        <?php echo $form->textField($model,'direction',array('maxlength'=>255, 'class' => 'input', 'style' => 'width: 300px')); ?>
                        <?php echo $form->error($model,'direction');?>
                    </div>
                </div>
                <div class="par control-group">
                    <?php echo $form->labelEx($model,'special_content', array('class' => 'control-label ')); ?>
                    <div class="controls">
                        <?php echo $form->textArea($model,'special_content',array('style' => 'width: 300px; height: 200px')); ?>
                        <?php echo $form->error($model,'special_content');?>
                    </div>
                </div>
                <div class="par control-group">
                    <?php echo $form->labelEx($model,'space', array('class' => 'control-label ')); ?>
                    <div class="controls">
                        <?php echo $form->textField($model,'space'); ?>
                        <?php echo $form->error($model,'space');?>
                    </div>
                </div>
                <div class="par control-group">
                    <?php echo $form->labelEx($model,'for_children', array('class' => 'control-label ')); ?>
                    <div class="controls">
                        <?php echo $form->checkBox($model,'for_children'); ?>
                    </div>
                </div>
                <div class="par control-group">
                    <?php echo $form->labelEx($model,'waiting', array('class' => 'control-label ')); ?>
                    <div class="controls">
                        <?php echo $form->dropDownList($model,'waiting',$model->waitingData); ?>
                        <?php echo $form->error($model,'waiting');?>
                    </div>
                </div>


                <script>
                    $(function(){
                        // select holiday by autocomplete
                        var holidayData = $.parseJSON('<?php echo json_encode(Branch::model()->holidayData)?>');
                        $("#Branch_holiday").autocomplete({
                            delay: 100,
                            minLength: 0,
                            source: function(request, response) {
                                var key = $.ui.autocomplete.escapeRegex($.trim(request.term));
                                var matcher = new RegExp(key, "i" );
                                var datas2 = new Array();
                                var i = 0;
                                $.each(holidayData, function(index, data){ 
                                    if ((matcher.test(data) || matcher.test(data.toAlias())) && i < 10){                   
                                        datas2[i] = {label:data,labelhl:data.highlight(key)};
                                        i++;      
                                    } 
                                });
                                //console.log(datas2);
                                response(datas2);
                            }, 
                            messages: {
                                noResults: '',
                                results: function() {}
                            },
                            //                            focus: function( event, ui ) {
                            //                                $(this).val( ui.item.label );
                            //                                return false;
                            //                            },
                            select: function( event, ui ) {;
                                $("#Branch_holiday").val(ui.item.value);
                                return false;
                            },
                            search: function(event, ui) { 

                            },
                        })
                        .data( "autocomplete" )._renderItem = function(ul, item) {
                            return $( "<li></li>" )
                            .data( "item.autocomplete", item )
                            .append( "<a style='cursor: pointer'>" + item.labelhl + "</a>")
                            .appendTo( ul );
                        }; 

                    });
                </script>


                <div class="par control-group">
                    <?php echo $form->labelEx($model,'holiday', array('class' => 'control-label ')); ?>
                    <div class="controls">
                        <?php echo $form->textField($model,'holiday'); ?>
                        <?php echo $form->error($model,'holiday');?>
                    </div>
                </div>
                <div class="par control-group">
                    <?php echo $form->labelEx($model,'year', array('class' => 'control-label ')); ?>
                    <div class="controls">
                        <?php echo $form->textField($model,'year'); ?>
                        <?php echo $form->error($model,'year');?>
                    </div>
                </div>
                <?php /*
                <div class="par control-group">
                    <?php echo $form->labelEx($model,'status', array('class' => 'control-label')); ?>
                    <div class="controls">
                        <?php echo $form->dropDownList($model, 'status', $model->statusData, array('class' => 'input uniformselect')); ?>
                        <?php echo $form->error($model,'status');?>                     
                    </div>
                </div>
                */?>
                <div class="par control-group">
                    <?php echo $form->labelEx($model,'insert_type', array('class' => 'control-label')); ?>
                    <div class="controls">
                        <?php echo $form->dropDownList($model, 'insert_type', $model->insertTypeData, array('class' => 'input uniformselect', 'disabled' => 'disabled')); ?>
                        <?php if($model->manager):?>
                            <div><?php echo $model->manager->email?></div>
                        <?php endif?>
                        <?php echo $form->error($model,'insert_type');?>                     
                    </div>
                </div>
                <div class="par control-group">
                    <label for="Branch_shop_name" class="control-label">Tổng comment</label>
                    <div class="controls">
                        <a class="label label-success" href="<?php echo $this->createUrl('/admin/comment', array('Comment[branch_id]' => $model->id))?>" target="_blank"><?php echo $model->comment_count?></a>
                    </div>
                </div>                
                <div class="par control-group">
                    <label for="Branch_shop_name" class="control-label">Tổng event</label>
                    <div class="controls">
                        <a class="label label-important" href="<?php echo $this->createUrl('/admin/event', array('Event[branch_id]' => $model->id))?>" target="_blank"><?php echo $model->event_count?></a>
                    </div>
                </div>
                <div class="par control-group">
                    <label for="Branch_shop_name" class="control-label">Số món thực đơn</label>
                    <div class="controls">
                        <a class="label label-info" href="<?php echo $this->createUrl('/admin/item', array('Item[branch_id]' => $model->id))?>" target="_blank"><?php echo $model->item_count?></a>
                    </div>
                </div>          
            </div>
        </div>
    </div>

    <div class="span6">
        <h4 class="widgettitle"><?php echo !$shop ? 'Ảnh cửa hàng' : 'Ảnh chi nhánh'?></h4>
        <div class="widgetcontent">
            <?php echo $form->error($model,'image', array('style' => 'margin-left: 0px'));?> 

            <link rel="stylesheet" href="/files/js/jquery.file.upload/css/bootstrap-image-gallery.min.css">
            <link rel="stylesheet" href="/files/js/jquery.file.upload/css/jquery.fileupload-ui.css">
            <!--[if lt IE 9]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
            <!-- The template to display files available for upload -->     
            <script id="template-upload" type="text/x-tmpl">
                {% for (var i=0, file; file=o.files[i]; i++) { %}
                <tr class="template-upload fade">
                    <td style="width: 0px"></td>
                    <td class="preview"><span class="fade"></span></td>
                    {% if (file.error) { %}
                    <td class="error" colspan="2"><span class="label label-important">Error</span> {%=file.error%}</td>
                    {% } else if (o.files.valid && !i) { %}
                    <td colspan="2">   
                        <div style="width: 120px" class="progress progress-success progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="bar" style="width:0%;"></div></div>
                        <div>{%=o.formatFileSize(file.size)%}</div>
                    </td>
                    <td>
                        <button class="btn btn-primary start" style="width: 82px">
                        <i class="icon-upload icon-white"></i>
                        <span>Upload</span>
                        </button>
                        {% if (!o.options.autoUpload) { %}
                        <br/>
                        <br/>
                        <button class="btn btn-warning cancel" style="width: 82px">
                            <i class="icon-ban-circle icon-white"></i>
                            <span>Dừng</span>
                        </button>
                        {% } %}
                    </td>
                    {% } %}
                </tr>
                {% } %}
            </script>

            <!-- The template to display files available for download -->
            <script id="template-download" type="text/x-tmpl"> 
                {% for (var i=0, file; file=o.files[i]; i++) { %}
                <tr class="group {%=file.group%} template-download fade ">
                    {% if (file.error) { %}
                        <td class="error" colspan="3"><span class="label label-important">Error</span> {%=file.error%}</td>
                    {% } else { %}
                        <td style="width: 0px"><input {% if (file.checked == 0) { %} disabled = "disabled" {% }%} class="image_cover" {% if (file.name == $.cookie('branch_form_img_cover')) { %} checked = "checked" {% }%}  type="radio" name="is_cover" value="{%=file.name%}" title="Chọn làm ảnh đại diện" /></td>
                        <td class="preview">
                            {% if (file.thumbnail_url) { %}
                            <a href="{%=file.url%}" title="{%=file.name%}" data-gallery="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>
                            {% } %}
                        </td>
                        <td class="image_status">
                            <input type="checkbox" value="1" {% if (file.checked == 1) { %} checked = "checked" {% }%} class="image_enable" name="enable[{%=file.id%}]" title="Hiển thị ảnh"/>
                        </td>
                        <td class="name">
                            <?php /*<a href="{%=file.url%}" title="{%=file.name%}" data-gallery="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a> */?>
                            <div class="image_group">
                            <select img_id="{%=file.id%}" id="image_group_{%=file.id%}" name="image_group[{%=file.id%}]">
                            <option value="FOOD"{% if (file.group == 'FOOD') { %} selected = "selected" {% }%}>Món ăn</option>
                            <option value="DECORATION"{% if (file.group == 'DECORATION') { %} selected = "selected" {% }%}>Bài trí</option>
                            <option value="MENU"{% if (file.group == 'MENU') { %} selected = "selected" {% }%}>Thực đơn</option>
                            <option value="OTHER"{% if (file.group == 'OTHER') { %} selected = "selected" {% }%}>Ảnh khác</option>
                            </select>
                            </div>
                        </td>
                    {% } %}

                    <td colspan="2">
                        <button class="badge badge-important delete" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}"{% if (file.delete_with_credentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
                            <i class="icon-trash icon-white"></i> <span>Xóa</span>
                        </button>
                        <input type="checkbox" name="delete" value="1" class="toggle">
                    </td>
                </tr>
                {% } %}
            </script>


            <script src="/files/js/jquery.file.upload/js/vendor/jquery.ui.widget.js"></script>
            <script src="/files/js/jquery.file.upload/js/vendor/tmpl.min.js"></script>
            <script src="/files/js/jquery.file.upload/js/vendor/load-image.min.js"></script>
            <script src="/files/js/jquery.file.upload/js/vendor/canvas-to-blob.min.js"></script>
            
            <script src="/files/js/jquery.file.upload/js/vendor/bootstrap-image-gallery.min.js"></script>
            
            <script src="/files/js/jquery.file.upload/js/jquery.iframe-transport.js"></script>
            <script src="/files/js/jquery.file.upload/js/jquery.fileupload.js"></script>
            <script src="/files/js/jquery.file.upload/js/jquery.fileupload-fp.js"></script>
            <script src="/files/js/jquery.file.upload/js/jquery.fileupload-ui.js"></script>
            
            <!--[if gte IE 8]><script src="js/cors/jquery.xdr-transport.js"></script><![endif]-->
            <script>
                $(function () {

                    'use strict';

                    // Initialize the jQuery File Upload widget:
                    $('#branch-form').fileupload({
                        // Uncomment the following to send cross-domain cookies:
                        xhrFields: {withCredentials: true},
                        url: '<?php $params = array('action' => $this->action->id);
                            if($model->id) $params['id'] = $model->id;
                            echo $this->createUrl('/admin/branch/upload', $params)?>'
                        });

                    // Load existing files:
                    $.ajax({
                        // Uncomment the following to send cross-domain cookies:
                        //xhrFields: {withCredentials: true},
                        url: $('#branch-form').fileupload('option', 'url'),
                        dataType: 'json',
                        context: $('#branch-form')[0]
                    }).done(function (result) {
                        $(this).fileupload('option', 'done')
                        .call(this, null, {result: result});
                    });

                    // save is_cover
                    $('input[name="is_cover"]').live('click', function(){
                        $.cookie('branch_form_img_cover', $(this).val());    
                    });

                    var branch_form_img_group = ($.cookie('branch_form_img_group') != undefined) ? JSON.parse($.cookie('branch_form_img_group')) : {};
                    $('select[id^="image_group_"]').live('change', function(){
                        branch_form_img_group[$(this).attr('img_id')] = $(this).val();
                        $.cookie('branch_form_img_group', JSON.stringify(branch_form_img_group));
                    });

                    // select tab
                    $('.tab-upload-image a').click(function(){
                        $('.tab-upload-image li').removeClass('active');
                        $(this).parent().addClass('active');

                        var group = $(this).attr('group');
                        if(group == 'ALL'){
                            $('tr.group').show();
                        }else{
                            $('tr.group').hide();
                            $('tr.group.'+group).show();
                        }
                    });

                    
                    // check enable image
                    $('.image_enable').live('click', function(){
                        var image_cover = $(this).parent().parent().find('.image_cover');
                        if($(this).is(':checked')){
                            image_cover.removeAttr('disabled');
                        }else{
                            image_cover.attr('disabled', 'disabled');
                            if(image_cover.is(':checked')){
                                image_cover.removeAttr('checked');    
                            } 
                        }  
                    });
                    
                    // check/uncheck all image
                    $('#enable_all_image').live('click', function(){
                        $(':checkbox.image_enable').prop('checked', this.checked);    
                        if(this.checked == true){
                            $(':radio.image_cover').removeAttr('disabled');
                        }else{
                            $(':radio.image_cover').attr('disabled', 'disabled');
                        } 
                    });
                });
            </script>


            <div class="fileupload-buttonbar clearfix">
                <span class="btn btn-success fileinput-button">
                    <i class="icon-plus icon-white"></i>
                    <span>Lấy ảnh từ máy tính...</span>
                    <input type="file" name="files[]" multiple>
                </span>
                <button type="button" class="btn btn-primary start">
                    <i class="icon-upload icon-white"></i>
                    <span>Upload tất cả</span>
                </button>
                <?php /*
                    <button type="reset" class="btn btn-warning cancel">
                    <i class="icon-ban-circle icon-white"></i>
                    <span>Dừng Upload</span>
                    </button>
                */?>
                <button type="button" class="btn btn-danger delete">
                    <i class="icon-trash icon-white"></i>
                    <span>Xóa</span>
                </button>
                <input type="checkbox" class="toggle">


                <?php /*
                    <div class="span5 fileupload-progress fade">
                    <div class="progress progress-success progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                    <div class="bar" style="width:0%;"></div>
                    </div>
                    <div class="progress-extended">&nbsp;</div>
                    </div>
                */?>
            </div>

            <div class="fileupload-loading"></div>

            <ul class="nav nav-tabs tab-upload-image">
                <li class="active"><a group="ALL">Tất cả (<?php echo $model->image_count?>)</a></li>
                <?php foreach(BranchImage::model()->getGroupData() as $k => $v):?>
                    <li><a group="<?php echo $k?>"><?php echo $v?></a></li>
                    <?php endforeach;?>
            </ul>
            <div class="shop-form-grid-images">
                <table role="presentation" class="table table-striped">
                    <tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery">
                        <tr class="group template-download">
                            <td></td>
                            <td></td>
                            <td colspan="4"><input title="check/uncheck all" type="checkbox" id="enable_all_image"/></td>
                        </tr>
                    </tbody>
                </table>
            </div>

        </div>
    </div>

</div>



<div id="modal-gallery" class="modal modal-gallery hide fade" tabindex="-1">
    <div class="modal-header">
        <a class="close" data-dismiss="modal">&times;</a>
        <h3 class="modal-title"></h3>
    </div>
    <div class="modal-body"><div class="modal-image"></div></div>
    <div class="modal-footer">
        <a class="btn modal-download" target="_blank">
            <i class="icon-download"></i>
            <span>Download</span>
        </a>
        <a class="btn btn-success modal-play modal-slideshow" data-slideshow="5000">
            <i class="icon-play icon-white"></i>
            <span>Slideshow</span>
        </a>
        <a class="btn btn-info modal-prev">
            <i class="icon-arrow-left icon-white"></i>
            <span>Trước</span>
        </a>
        <a class="btn btn-primary modal-next">
            <span>Kế tiếp</span>
            <i class="icon-arrow-right icon-white"></i>
        </a>
    </div>
</div>

<div class="row-fluid">
    <div class="span7">
        <h4 class="widgettitle"><?php echo !$shop ? 'Tọa độ cửa hàng' : 'Tọa độ chi nhánh'?></h4>
        <div class="widgetcontent">
            <div id="map" style="float:left; width: 548px; height: 300px; box-shadow: 2px 2px 6px #AAAAAA;">
                <div style="text-align: center; line-height: 300px; color: #999">Tải bản đồ từ google ...</div>
            </div>            
        </div>
    </div>
    <div class="span5">
        <h4 class="widgettitle"><?php echo !$shop ? 'Địa chỉ cửa hàng' : 'Địa chỉ chi nhánh'?></h4>
        <div class="widgetcontent">

            <div class="par control-group">
                <?php echo $form->labelEx($model,'city_id', array('class' => 'control-label')); ?>
                <div class="controls">
                    <?php echo $form->dropDownList($model,'city_id', $citiesData, array('class' => 'input')); ?>
                    <?php echo $form->error($model,'city_id');?>
                </div>
            </div>

            <div class="par control-group">
                <?php echo $form->labelEx($model,'district_id', array('class' => 'control-label')); ?>
                <div class="controls">
                    <?php echo $form->dropDownList($model,'district_id', $districtsData, array('class' => '')); ?>
                    <?php echo $form->error($model,'district_id');?>
                </div>
            </div>
            <div class="par control-group">
                <?php echo $form->labelEx($model,'address', array('class' => 'control-label')); ?>
                <div class="controls">
                    <?php echo $form->textField($model,'address', array(), array('class' => '')); ?>
                    <?php echo $form->error($model,'address');?>
                </div>
            </div>
            <div class="par control-group">
                <label>Xem trước</label>
                <div class="controls">
                    <?php echo CHtml::textField('address_full', NULL, array('class' => 'input uniformselect', 'disabled'=>'disabled'));?>    
                </div>
            </div>

            <div class="par control-group">
                <?php echo $form->labelEx($model,'publicLocations', array('class' => 'control-label')); ?>
                <div class="controls">
                    <?php echo $form->dropDownList($model,'publicLocations', $locationsData, array('maxlength'=>255, 'class' => '', 'multiple' => 'multiple', 'size' => 5)); ?>
                    <?php echo $form->error($model,'publicLocations');?>
                </div>
            </div>

            <div class="par control-group">
                <?php echo $form->labelEx($model,'latlng', array('class' => 'control-label')); ?>
                <div class="controls">
                    <?php echo $form->hiddenField($model,'latlng'); ?>
                    <?php echo CHtml::textField('latlng_view', $model->latlng, array('class' => 'input uniformselect', 'disabled'=>'disabled')); ?>
                    <?php echo $form->error($model,'latlng');?>
                </div>
            </div>

        </div>
    </div>
</div>


<script>
    $(function(){
        $('.param-parent .toogle').click(function(){
            $(this).parent().find('.param-childs').toggle('fast', function(){
                if($(this).is(":visible")){
                    $(this).parent().find('.toogle').html(' [<i class="icon-arrow-up"></i>]');    
                }else{
                    $(this).parent().find('.toogle').html(' [<i class="icon-arrow-down"></i>]');
                }
            });
        });
        $('.param-has-childs').click(function(){
            // slide down childs
            if($(this).is(':checked')){
                $(this).parent().find('.param-childs').slideDown('fast');
                $(this).parent().find('.toogle').html(' [<i class="icon-arrow-up"></i>]');    
            }

            // can't uncheck if has checked child 
            var hasChildSelected = false;
            $(this).parent().find('.param-is-child').each(function(index){
                if($(this).is(':checked')){
                    hasChildSelected = true;
                    return false;
                }
            });
            if(hasChildSelected == true){
                $(this).attr('checked', true);       
            }   
        });
        $('.param-is-child').click(function(){
            if($(this).is(':checked')){
                $(this).parent().parent().parent().find('.param-has-childs').attr('checked', true);    
            }
        });

    })
</script>
<div class="row-fluid" style="margin-top: 30px;">                                                                      
    <div class="span12">
        <h4 class="widgettitle">Bộ thuộc tính</h4>
        <div class="widgetcontent">
            <?php foreach(ParamGroup::model()->getAll() as $group):?>
                <div class="row-fluid param-group">
                    <div class="span2">
                        <div class="label"><?php echo $group->name?></div>
                    </div>

                    <div class="span10">
                        <?php foreach($group->params as $parentParam):?>
                            <div class="param-parent">
                                <?php $option = array('value' => $parentParam->id, 'id' => 'Branch_params_'.$parentParam->id);
                                    if($parentParam->params) $option['class'] = 'param-has-childs';    
                                    echo CHtml::checkBox('Branch[params][]', in_array($parentParam->id, $paramIdData), $option); ?>
                                <?php echo $parentParam->name?> 

                                <?php if($parentParam->params):?>
                                    <span class="toogle"> [<i class="icon-arrow-down"></i>]</span>
                                    <div class="param-childs">
                                        <?php foreach($parentParam->params as $param):?>
                                            <div class="param-child">
                                                <?php echo CHtml::checkBox('Branch[params][]', in_array($param->id, $paramIdData), array('value' => $param->id, 'id' => 'Branch_params_'.$param->id, 'class' => 'param-is-child')); ?>
                                                <?php echo $param->name?>
                                            </div>
                                            <?php endforeach?>
                                    </div>
                                    <?php endif?>

                            </div>
                            <?php endforeach?>
                    </div>
                </div>
                <hr/> 
                <?php endforeach?>

        </div>
    </div>
</div>
<p>
    <button class="btn btn-info btn-large" type="submit"><?php echo !$shop ? 'Tạo cửa hàng' : 'Cập nhật'?>  </button>
</p>
<?php $this->endWidget(); ?>